package com.bleeth.flow.core;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import com.bleeth.flow.core.common.APlugin;
import com.bleeth.flow.core.common.FlowTask;
import com.bleeth.flow.core.util.PluginUtil;

import java.io.File;
import java.nio.charset.Charset;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author ：Bleeth
 * @date ：2021-08-06
 * @description：Flow相关工具类
 */
public class FlowApp {


    private static Map<String, FlowTask> flowMap = new ConcurrentHashMap();

    /**
     * 从json中解析任务流程
     *
     * @param flowJson 任务流，配置文件内容
     * @return 一个可执行的任务流
     */
    public static FlowTask parseFlow(String flowJson) {
        JSONObject json = new JSONObject(flowJson);
        String flowName = json.getStr("name");
        String uuid = json.getStr("uuid");
        String cron = json.getStr("cron");
        JSONArray job = json.getJSONArray("job");
        JSONObject options = json.getJSONObject("options");

        FlowTask flowTask = FlowTask
                .builder()
                .flowName(flowName)
                .flowUid(uuid)
                .options(options)
                .flowCron(cron)
                .create();

        //解析json中的插件
        for (int i = 0; i < job.size(); i++) {
            JSONObject object = job.getJSONObject(i);
            String id = object.getStr("id");
            APlugin p = PluginUtil.getPluginMap().get(id);
            APlugin plugin = object.toBean(p.getClass());

            /**
             * 执行插件的初始化
             */
            plugin.init();

            String name = plugin.getName();
            flowTask.addPlugin(name, plugin);
        }

        //生成WorkerWrapper
        try {
            flowTask.buildWrapper(true);
        } catch (Exception e) {
            e.printStackTrace();
        }

        //将其添加到flow流程中进行管理
        flowMap.put(flowTask.getFlowUid(), flowTask);
        return flowTask;
    }

    public static FlowTask parseFlow(String flowPath, String charset) {
        String jsonContent = FileUtil.readString(new File(flowPath), Charset.forName(charset));
        return parseFlow(jsonContent);
    }


    public static Map<String, FlowTask> getRegisterFlow() {
        return flowMap;
    }

    public static FlowTask create(String flowName) {
        String uuid = IdUtil.fastSimpleUUID();
        FlowTask flowTask = FlowTask
                .builder()
                .flowName(flowName)
                .flowUid(uuid)
                .create();
        return flowTask;
    }
}
